//
//  TheMoveView.m
//  量角器
//
//  Created by zhaoyf on 2021/8/3.
//

#import "TheMoveView.h"

@implementation TheMoveView

-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.userInteractionEnabled = YES;
    }
    return self;
}


-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    //计算位移=当前位置-起始位置
    CGPoint point = [[touches anyObject] locationInView:self];
    float dx = point.x - self.startPoint.x;
    float dy = point.y - self.startPoint.y;
    
    //计算移动后的view中心点
    CGPoint newcenter = CGPointMake(self.center.x + dx, self.center.y + dy);
    
    
    /* 限制用户不可将视图托出屏幕 */
    float halfx = CGRectGetMidX(self.bounds);
    //x坐标左边界
    newcenter.x = MAX(halfx, newcenter.x);
    //x坐标右边界
    newcenter.x = MIN(self.superview.bounds.size.width - halfx, newcenter.x);
    
    //y坐标同理
    float halfy = CGRectGetMidY(self.bounds);
    newcenter.y = MAX(halfy, newcenter.y);
    newcenter.y = MIN(self.superview.bounds.size.height - halfy, newcenter.y);
    self.newPoint = newcenter;
//    NSLog(@"x%f-y%f",self.newPoint.x,self.newPoint.y);
    //移动view
    if (self.moveBlock) {
        self.moveBlock([[MNPoint alloc] initWithX:self.newPoint.x andY:self.newPoint.y]);
    }
    self.center = newcenter;
}

@end
